<template>
  <div class="min-h-200 flex flex-col gap-y-24">
    <div class="flex items-center gap-x-10">
      <div class="font-size-14 color-#3A3E45 font-bold">商机来源</div>
      <MyLink
        v-if="detail.opportunityId"
        :text="detail.opportunityName"
        :target="{ path: `/niche/detail`, query: { id: detail.opportunityId } }"
      />
      <div v-else>无</div>
    </div>
    <div class="flex flex-col gap-y-12">
      <div class="flex items-center gap-x-10">
        <div class="font-size-14 color-#3A3E45 font-bold">关于项目</div>
        <div
          v-permission="`about_project`"
          class="edit box-border h-24 w-24 cursor-pointer rounded-4 bg-#F4F5F7 p-4"
          @click="handleEditProject(detail)"
        >
          <img src="@/assets/icons/edit.png" />
        </div>
      </div>
      <n-table :single-line="false">
        <tbody>
          <tr v-for="(item, index) in detail.customerManagementDtoList" :key="index">
            <td class="text-nowrap">客户{{ index + 1 }}:</td>
            <td class="break-all">{{ item.name }}</td>
            <td class="text-nowrap">对接人:</td>
            <td class="break-all">
              {{
                item.contactorDtoList
                  .map((i) => `${i.contactorName} ${i.contactorPhone || '--'}；`)
                  .join('')
              }}
            </td>
          </tr>
          <tr>
            <td class="text-nowrap">商机名称:</td>
            <td class="break-all">{{ detail.opportunityName || '--' }}</td>
            <td class="text-nowrap">项目创建时间</td>
            <td class="break-all">{{ $format(detail.createTime) || '--' }}</td>
          </tr>
          <tr>
            <td class="text-nowrap">项目描述:</td>
            <td class="break-all" colspan="3">{{ detail.projectResume || '--' }}</td>
          </tr>
          <tr>
            <td class="text-nowrap">项目注意:</td>
            <td class="break-all" colspan="3">{{ detail.projectNote || '--' }}</td>
          </tr>
        </tbody>
      </n-table>
    </div>
    <div class="flex flex-col gap-y-12">
      <div class="font-size-14 color-#3A3E45 font-bold">项目附件</div>
      <FileList :model-value="detail.projectFileDtoList" :show-remove="false" />
    </div>
    <div class="flex flex-col gap-y-12">
      <div class="flex items-center gap-x-10">
        <div class="font-size-14 color-#3A3E45 font-bold">关于交付</div>
        <div
          v-permission="`about_deliver`"
          class="edit box-border h-24 w-24 cursor-pointer rounded-4 bg-#F4F5F7 p-4"
          @click="handleEditDeliver(detail)"
        >
          <img src="@/assets/icons/edit.png" />
        </div>
      </div>
      <n-table :single-line="false">
        <tbody>
          <tr>
            <td class="text-nowrap">启动时间:</td>
            <td class="break-all">{{ $format(detail.projectStartNode) || '--' }}</td>
            <td class="text-nowrap">客户提测节点</td>
            <td class="break-all">{{ $format(detail.customerTestNode) || '--' }}</td>
          </tr>
          <tr>
            <td class="text-nowrap">内部提测节点:</td>
            <td class="break-all">{{ $format(detail.insideTestNode) || '--' }}</td>
            <td class="text-nowrap">上线节点:</td>
            <td class="break-all">{{ $format(detail.releaseTestNode) || '--' }}</td>
          </tr>
          <tr>
            <td rowspan="2" class="text-nowrap">交付物说明:</td>
            <td colspan="3" class="break-all">{{ detail.deliverablesDescription || '--' }}</td>
          </tr>
          <tr>
            <td>
              <FileList :model-value="detail.deliverablesFileDtoList" :show-remove="false" />
            </td>
          </tr>
        </tbody>
      </n-table>
    </div>
    <div class="flex flex-col gap-y-12">
      <div class="flex items-center gap-x-10">
        <div class="font-size-14 color-#3A3E45 font-bold">关于安排</div>
        <div
          v-permission="`about_person`"
          class="edit box-border h-24 w-24 cursor-pointer rounded-4 bg-#F4F5F7 p-4"
          @click="handleEditPerson(detail)"
        >
          <img src="@/assets/icons/edit.png" />
        </div>
      </div>
      <div>研发负责组：{{ detail.developGroupName }}</div>
      <n-data-table
        :columns="columns"
        :data="detail.projectPersonDtoList"
        :row-key="(row) => row['id']"
      />
    </div>
    <!-- 关于项目表单 -->
    <MyDrawer
      key="project"
      ref="$formProject"
      :model-form="modelProject"
      :width="900"
      @submit="handleSubmitProject"
    >
      <n-form-item label="对接客户" path="customerManagementDtoList">
        <Customer
          v-model="modelProject.customerManagementDtoList"
          parent-key="customerManagementDtoList"
        />
      </n-form-item>
      <n-form-item label="商机名称" path="opportunityName">
        <n-input
          v-model:value="modelProject.opportunityName"
          maxlength="50"
          show-count
          clearable
          :disabled="true"
        />
      </n-form-item>
      <n-form-item label="项目描述" path="projectResume">
        <n-input
          v-model:value="modelProject.projectResume"
          clearable
          :maxlength="300"
          show-count
          type="textarea"
          :autosize="{
            minRows: 3,
          }"
        />
      </n-form-item>
      <n-form-item label="项目注意" path="projectNote">
        <n-input
          v-model:value="modelProject.projectNote"
          clearable
          :maxlength="300"
          show-count
          type="textarea"
          :autosize="{
            minRows: 3,
          }"
        />
      </n-form-item>
      <n-form-item label="项目附件" path="projectFileDtoList">
        <FileUpload v-model="modelProject.projectFileDtoList" />
      </n-form-item>
    </MyDrawer>
    <!-- 关于交付表单 -->
    <MyDrawer
      key="deliver"
      ref="$formDeliver"
      :model-form="modelDeliver"
      :width="700"
      @submit="handleSubmitDeliver"
    >
      <n-form-item label="客户提测节点" path="customerTestNode">
        <n-date-picker
          v-model:formatted-value="modelDeliver.customerTestNode"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm"
          :time-picker-props="{ format: 'HH:mm' }"
          placeholder="选择时间"
          clearable
        />
      </n-form-item>
      <n-form-item label="内部提测节点" path="insideTestNode">
        <n-date-picker
          v-model:formatted-value="modelDeliver.insideTestNode"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm"
          :time-picker-props="{ format: 'HH:mm' }"
          placeholder="选择时间"
          clearable
        />
      </n-form-item>
      <n-form-item label="上线节点" path="releaseTestNode">
        <n-date-picker
          v-model:formatted-value="modelDeliver.releaseTestNode"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm"
          :time-picker-props="{ format: 'HH:mm' }"
          placeholder="选择时间"
          clearable
        />
      </n-form-item>
      <n-form-item label="交付物说明" path="deliverablesDescription">
        <n-input
          v-model:value="modelDeliver.deliverablesDescription"
          clearable
          :maxlength="300"
          show-count
          type="textarea"
          :autosize="{
            minRows: 3,
          }"
        />
      </n-form-item>
      <n-form-item label="交付物附件" path="deliverablesFileDtoList">
        <FileUpload v-model="modelDeliver.deliverablesFileDtoList" />
      </n-form-item>
    </MyDrawer>
    <!-- 关于安排表单 -->
    <MyDrawer
      key="person"
      ref="$formPerson"
      :model-form="modelPerson"
      :width="1100"
      @submit="handleSubmitPerson"
    >
      <n-form-item label="研发负责组" path="developGroup">
        <AsyncSelect
          v-model:value="modelPerson.developGroup"
          label-key="name"
          value-key="deptId"
          :options="devDeptOptions"
          placeholder="请设置研发负责组"
          style="width: 400px"
        />
        <div v-if="modelPerson.developGroup" class="ml-20">
          (组长：{{ groupLeader.leaderName || '暂无' }})
        </div>
      </n-form-item>
      <n-form-item
        label="人员安排"
        path="projectPersonDtoList"
        :rule="{ validator: validatorPerson }"
      >
        <Member v-model="modelPerson.projectPersonDtoList" :group-id="groupLeader?.deptId || ''" />
      </n-form-item>
    </MyDrawer>
    <!-- 关于安排单独表单 -->
    <MyDrawer
      key="personItem"
      ref="$formPersonItem"
      :model-form="modelPersonItem"
      @submit="handleSubmitPersonItem"
    >
      <n-form-item label="贡献度" path="contribution">
        <n-input-number v-model:value="modelPersonItem.contribution" :max="100" clearable />
      </n-form-item>
      <n-form-item label="贡献度描述" path="contributionDescription">
        <n-input
          v-model:value="modelPersonItem.contributionDescription"
          clearable
          :maxlength="300"
          show-count
          type="textarea"
          :autosize="{
            minRows: 3,
          }"
        />
      </n-form-item>
    </MyDrawer>
  </div>
</template>
<script setup lang="jsx">
import { useCrudPro } from '@/hooks/useCrudPro'
import * as projectApi from '@/api/project'
import { formatToIds, formatToSel } from '@/utils/format'
defineOptions({ name: 'ProjectInfo' })
const emits = defineEmits(['reset'])
const props = defineProps({
  detail: {
    type: Object,
    default: () => ({}),
  },
})
const columns = [
  {
    title: '序号',
    width: 80,
    key: 'index',
    render: (_, index) => index + 1,
  },
  {
    title: '人员',
    key: 'personName',
  },
  {
    title: '组别',
    key: 'groupName',
  },
  {
    title: '岗位',
    key: 'positionName',
  },
  {
    title: '执行',
    key: 'executeName',
  },
  {
    title: '执行范围',
    key: 'executeRangeName',
  },
  {
    title: '实际工期',
    key: 'duration',
  },
  {
    title: '贡献度',
    key: 'contribution',
    render: ({ contribution }) => `${contribution || 0}%`,
  },
  {
    title: '贡献度描述',
    key: 'contributionDescription',
    width: 300,
    ellipsis: {
      tooltip: {
        style: {
          maxWidth: '300px',
        },
      },
    },
  },
  {
    title: '操作',
    key: 'action',
    render(row) {
      return (
        <n-button
          v-permission="about_person_contribution"
          text
          onClick={() => handleEditPersonItem(row)}
        >
          修改
        </n-button>
      )
    },
  },
]
function validatorPerson(_, value, callback) {
  if (Array.isArray(value) && value.length) {
    if (value.some((item) => !item.personId)) {
      callback(new Error('请选择人员!'))
    } else if (value.some((item) => !item.executeRangeCode.length)) {
      callback(new Error('请选择执行范围!'))
    } else if (value.length !== [...new Set(value.map((item) => item.personId))].length) {
      callback(new Error('存在重复人员!'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

//关于项目
const {
  model: modelProject,
  $form: $formProject,
  handleEdit: handleEditProject,
  handleSubmit: handleSubmitProject,
} = useCrudPro({
  title: '关于项目',
  initForm: {
    id: null,
    customerManagementDtoList: [],
    opportunityName: null,
    projectResume: null,
    projectNote: null,
    projectFileDtoList: [],
  },
  apis: {
    edit: projectApi.aboutProject,
    info: (info) => {
      info.customerManagementDtoList = props?.detail?.customerManagementDtoList || []
      return info
    },
  },
  handleChange() {
    $message.success('关于项目修改成功！')
    emits('reset')
  },
})

//关于交付
const {
  model: modelDeliver,
  $form: $formDeliver,
  handleEdit: handleEditDeliver,
  handleSubmit: handleSubmitDeliver,
} = useCrudPro({
  title: '关于交付',
  initForm: {
    id: null,
    customerTestNode: null,
    insideTestNode: null,
    releaseTestNode: null,
    deliverablesDescription: null,
    deliverablesFileDtoList: [],
  },
  apis: {
    edit: projectApi.aboutDeliver,
  },
  handleChange() {
    $message.success('关于交付修改成功！')
    emits('reset')
  },
})

//关于安排
const groupLeader = ref({})
const devDeptOptions = ref([])
async function getDevDeptOptions() {
  const { data } = await projectApi.devDeptList()
  devDeptOptions.value = data
}
onBeforeMount(() => {
  getDevDeptOptions()
})
watchEffect(() => {
  groupLeader.value =
    devDeptOptions.value?.find((item) => item.deptId === modelPerson.value.developGroup) || {}
})
const {
  model: modelPerson,
  $form: $formPerson,
  handleEdit: handleEditPerson,
  handleSubmit: handleSubmitPerson,
} = useCrudPro({
  title: '关于安排',
  initForm: {
    id: null,
    developGroup: null,
    projectPersonDtoList: [],
  },
  apis: {
    edit: projectApi.aboutPerson,
    info: (info) => {
      groupLeader.value = info.developmentHeader
      info.projectPersonDtoList = (info?.projectPersonDtoList || []).map((item) => ({
        ...item,
        executeRangeCode: formatToSel(item.executeRangeCode),
      }))
      return info
    },
  },
  formatParams(params) {
    params.projectPersonDtoList = (params?.projectPersonDtoList || []).map((item) => ({
      ...item,
      executeRangeCode: formatToIds(item.executeRangeCode),
    }))
    return params
  },
  handleChange() {
    $message.success('关于安排修改成功！')
    emits('reset')
  },
})

//关于安排单独
const {
  model: modelPersonItem,
  $form: $formPersonItem,
  handleEdit: handleEditPersonItem,
  handleSubmit: handleSubmitPersonItem,
} = useCrudPro({
  name: '人员',
  initForm: {
    id: null,
    contribution: null,
    contributionDescription: null,
  },
  apis: {
    edit: projectApi.aboutPersonEdit,
  },
  handleChange() {
    $message.success('修改人员成功！')
    emits('reset')
  },
})
</script>
<style lang="scss" scoped></style>
